<?php
class CFlashcommon
{
	public function getAvaiAmount($uid)
	{
		$mlmMember = new CMlmmember();
		$row = $mlmMember->fetchRow(array('uid = ?'=>$uid));
		if (!$row) {
			return 0;
		}
		$mlm = new CMlm();
		$inProcess = $mlm->getInProcessCash($uid);		
		return $row->cash - $inProcess;
	}
	
	public function getAvaiItemCount($uid)
	{
		$memberAttr = new CMemberattr();
		$row = $memberAttr->fetchRow(array('uid = ?'=>$uid, 'attr_name = ?'=>'flash_item'));
		if (!$row) {
			return 0;
		}
		return $row->attr_value;
	}
	
	public function getAvaiWhenEverItemCount($uid)
	{
		$memberAttr = new CMemberattr();
		$row = $memberAttr->fetchRow(array('uid = ?'=>$uid, 'attr_name = ?'=>'flash_wheneveritem'));
		if (!$row) {
			return 0;
		}
		return $row->attr_value;
	}
	
	public function buyItem($uid, $count)
	{
		$amount = $count * 0.1;
		$avaiAmount = $this->getAvaiAmount($uid);
		if ($amount > $avaiAmount) {
			return false;
		}
		if (!$uid) {
			return false;
		}
		try {
			$memberAttr = new CMemberattr();
			$row = $memberAttr->fetchRow(array('uid = ?'=>$uid, 'attr_name = ?'=>'flash_item'));
			$db = $memberAttr->getAdapter();
			//扣钱
			$sql = 'update zcshop_mlm_member set cash=cash-' . $amount . ', update_time=' . time() . ' where uid = ' . intval($uid);
			$db->query($sql);
			$flashItemLog = new CFlashitemlog();
			$flashItemLog->insert(array('uid'=>$uid, 'buy_count'=>$count, 'type'=>1, 'add_time'=>time()));
			//增加item
			if (!$row) {
				$memberAttr->insert(array('uid'=>$uid, 'attr_name'=>'flash_item', 'attr_value'=>$count, 'add_time'=>time()));
			} else {
				$memberAttr->update(array('attr_value'=>new Zend_Db_Expr('attr_value + ' . $count)), 'uid = ' . intval($uid) . ' and attr_name = "flash_item"');
			}
			return true;
		} catch (Exception $e) {
			print_r($e->getMessage());exit();
			return false;
		}
	}
	
	public function buyWhenEverItem($uid, $count)
	{
		$amount = $count * 0.2;
		$avaiAmount = $this->getAvaiAmount($uid);
		if ($amount > $avaiAmount) {
			return false;
		}
		if (!$uid) {
			return false;
		}
		try {
			$memberAttr = new CMemberattr();
			$row = $memberAttr->fetchRow(array('uid = ?'=>$uid, 'attr_name = ?'=>'flash_wheneveritem'));
			$db = $memberAttr->getAdapter();
			//扣钱
			$sql = 'update zcshop_mlm_member set cash=cash-' . $amount . ', update_time=' . time() . ' where uid = ' . intval($uid);
			$db->query($sql);
			$flashItemLog = new CFlashitemlog();
			$flashItemLog->insert(array('uid'=>$uid, 'buy_count'=>$count, 'type'=>0, 'add_time'=>time()));
			//增加item
			if (!$row) {
				$memberAttr->insert(array('uid'=>$uid, 'attr_name'=>'flash_wheneveritem', 'attr_value'=>$count, 'add_time'=>time()));
			} else {
				$memberAttr->update(array('attr_value'=>new Zend_Db_Expr('attr_value + ' . $count)), 'uid = ' . intval($uid) . ' and attr_name = "flash_wheneveritem"');
			}
			return true;
		} catch (Exception $e) {
			print_r($e->getMessage());exit();
			return false;
		}
	}
	
	public function addItem($uid, $count)
	{
		if (!$uid) {
			return;
		}
		try {
			$memberAttr = new CMemberattr();
			$row = $memberAttr->fetchRow(array('uid = ?'=>$uid, 'attr_name = ?'=>'flash_item'));
			$db = $memberAttr->getAdapter();			
			//增加item
			if (!$row) {
				$memberAttr->insert(array('uid'=>$uid, 'attr_name'=>'flash_item', 'attr_value'=>$count, 'add_time'=>time()));
			} else {
				$memberAttr->update(array('attr_value'=>new Zend_Db_Expr('attr_value + ' . $count)), 'uid = ' . intval($uid) . ' and attr_name = "flash_item"');
			}
			return true;
		} catch (Exception $e) {
			print_r($e->getMessage());exit();
			return false;
		}
	}
	
	public function getItem($uid)
	{
		if ($this->getAvaiItemCount($uid) > 0) {
			$flashSale = new CFlashsales();
			$endTime = $flashSale->getTime('end');
			//闪购未开始
			if($endTime == -1) {
				return false;
			}
			
			$flashItem = new CFlashitem();
			$db = $flashItem->getAdapter();
			$sql = 'select flid from zcshop_productfls where pid=92 or pid=93';
			$rows = $db->fetchAll($sql);	
			$flids = array();
			foreach ($rows as $v) {
				$flids[] = $v['flid'];
			}	
			
			$expRows = $db->fetchAll('select itemid from zcshop_product_attr where attr_id_ex in(13)');
			$exparr = array();
			foreach ($expRows as $v) {
				$exparr[] = $v['itemid'];
			}			
			$exp = implode(',', $exparr);
			
			foreach ($flids as $v) {
				if ($exp) {
					$sql = "select p.itemid from zcshop_products p inner join zcshop_items i on i.itemid=p.itemid inner join zcshop_product_attr a on a.itemid=p.itemid  where p.is_showed=1 and p.onsales=0 and i.subject not like'%#%' and i.flid = $v and p.itemid not in($exp) order by rand() limit 1";
				} else {
					$sql = "select p.itemid from zcshop_products p inner join zcshop_items i on i.itemid=p.itemid inner join zcshop_product_attr a on a.itemid=p.itemid  where p.is_showed=1 and p.onsales=0 and i.subject not like'%#%' and i.flid =$v and a.attr_id_ex not in(13) order by rand() limit 1";
				}
				//echo $sql . '<br>';
				$rows = $db->fetchAll($sql);	
				foreach ($rows as $_v) {
					$return[] = $_v;
				}
			}
			$flag = true;
			while ($flag) {
				$num = rand(0, count($return)-1);		
				$itemId = $return[$num]['itemid'];
				$tmp = $flashItem->fetchRow(array('uid = ?'=>$uid, 'itemid = ?'=>$itemId, 'statu = ?'=>1));
				if(!$tmp) {
					$flag = false;
				}
			}
			//随机生成itemid并减少数目
			$flashItem->insert(array('uid'=>$uid, 'itemid'=>$itemId,'expiretime'=>$endTime, 'statu'=>1));
			$memberAttr = new CMemberattr();
			$memberAttr->update(array('attr_value'=>new Zend_Db_Expr('attr_value - 1 ')), 'uid = ' . intval($uid) . ' and attr_name = "flash_item"');
			$itemModel = new CItem();
			$item = $itemModel->getDetail($itemId, 'product');
			if ($this->isSuit($itemId)) {
				$item[0]['is_suit'] = 1;
			} else {
				$item[0]['is_suit'] = 0;
			}
			return $item;
		}
		return false;
	}
	
	public function isUserFlashItem($uid, $itemid)
	{
		$flashItem = new CFlashitem();
		$row = $flashItem->fetchRow(array('itemid = ?'=>$itemid, 'uid = ?'=>$uid, 'statu = ?'=>'1'));
		
		if ($row) {
			return true;
		}		
		return false;
	}
	
	public function isUserWhenEverFlashItem($uid, $itemid)
	{
		$flashItem = new CFlashwheneveritem();
		$flashItem->update(array('statu'=>0), 'expiretime<' . time() . ' and statu=1');
		$row = $flashItem->fetchRow(array('itemid = ?'=>$itemid, 'uid = ?'=>$uid, 'statu = ?'=>'1'));
		if ($row) {
			return true;
		}
		return false;
	}
	
	public function getCurFlashItem($uid)
	{
		$flashItem = new CFlashitem();
		$row = $flashItem->fetchAll(array('uid = ?'=>$uid, 'statu = ?'=>'1'));
		$ids = array();
		foreach ($row as $v) {
			$ids[] = $v->itemid;
		}
		
		
		$itemId = implode(',', $ids);
		if (!$itemId) {
			return array();
		}
		$itemShow=new CItemShow();
        $itemShow->setType('product');
        $itemShow->setWhere(R_PRE."items.itemid in (" . $itemId . ")");
        $result = $itemShow->getAllItems();    
        $flashSaleCommon = new CFlashsales();
        $return = array();
        foreach ($result as $v) {
        	$discount = $flashSaleCommon->getDiscount($v['itemid']);
        	$v['max_price'] = round($v['max_price'] * $discount,2);
        	if ($this->isSuit($v['itemid'])) {
        		$v['is_suit'] = 1;
        	} else {
        		$v['is_suit'] = 0;
        	}
        	$return[] = $v;
        }
        return $return;
	}
	
	public function getWhenEverItem($uid)
	{
		if ($this->getAvaiWhenEverItemCount($uid) > 0) {
			$flashSale = new CFlashsales();
			$endTime = $flashSale->getTime('end');
			
			
			$flashItem = new CFlashwheneveritem();
			$db = $flashItem->getAdapter();
			$sql = 'select flid from zcshop_productfls where pid=92 or pid=93';
			$rows = $db->fetchAll($sql);	
			$flids = array();
			foreach ($rows as $v) {
				$flids[] = $v['flid'];
			}	
			
			$expRows = $db->fetchAll('select itemid from zcshop_product_attr where attr_id_ex in(13)');
			$exparr = array();
			foreach ($expRows as $v) {
				$exparr[] = $v['itemid'];
			}			
			$exp = implode(',', $exparr);
			
			foreach ($flids as $v) {
				if ($exp) {
					$sql = "select p.itemid from zcshop_products p inner join zcshop_items i on i.itemid=p.itemid inner join zcshop_product_attr a on a.itemid=p.itemid  where p.is_showed=1 and p.onsales=0 and i.subject not like'%#%' and i.flid = $v and p.itemid not in($exp) order by rand() limit 1";
				} else {
					$sql = "select p.itemid from zcshop_products p inner join zcshop_items i on i.itemid=p.itemid inner join zcshop_product_attr a on a.itemid=p.itemid  where p.is_showed=1 and p.onsales=0 and i.subject not like'%#%' and i.flid = $v and a.attr_id_ex not in(13) order by rand() limit 1";
				}
					
				//echo $sql . '<br>';
				$rows = $db->fetchAll($sql);	
				foreach ($rows as $_v) {
					$return[] = $_v;
				}
			}
			$flag = true;
			while ($flag) {
				$num = rand(0, count($return)-1);		
				$itemId = $return[$num]['itemid'];
				$tmp = $flashItem->fetchRow(array('uid = ?'=>$uid, 'itemid = ?'=>$itemId, 'statu = ?'=>1));
				if(!$tmp) {
					$flag = false;
				}
			}
			//随机生成itemid并减少数目
			$flashItem->insert(array('uid'=>$uid, 'itemid'=>$itemId,'expiretime'=>time()+3600, 'statu'=>1));
			$memberAttr = new CMemberattr();
			$memberAttr->update(array('attr_value'=>new Zend_Db_Expr('attr_value - 1 ')), 'uid = ' . intval($uid) . ' and attr_name = "flash_wheneveritem"');
			$itemModel = new CItem();
			$item = $itemModel->getDetail($itemId, 'product');
			if ($this->isSuit($itemId)) {
				$item[0]['is_suit'] = 1;
			} else {
				$item[0]['is_suit'] = 0;
			}
			return $item;
		}
		return false;
	}
	
	public function getCurFlashWhenEverItem($uid)
	{
		$flashItem = new CFlashwheneveritem();
		$flashItem->update(array('statu'=>0), 'expiretime<' . time() . ' and statu=1');
		$row = $flashItem->fetchAll(array('uid = ?'=>$uid, 'statu = ?'=>'1'));
		$ids = array();
		foreach ($row as $v) {
			$ids[] = $v->itemid;
		}
		
		
		$itemId = implode(',', $ids);
		if (!$itemId) {
			return array();
		}
		$itemShow=new CItemShow();
        $itemShow->setType('product');
        $itemShow->setWhere(R_PRE."items.itemid in (" . $itemId . ")");
        $result = $itemShow->getAllItems();    
        $flashSaleCommon = new CFlashsales();
        $return = array();
        foreach ($result as $v) {
        	$discount = $flashSaleCommon->getDiscount($v['itemid']);
        	$v['max_price'] = round($v['max_price'] * $discount,2);
        	if ($this->isSuit($v['itemid'])) {
        		$v['is_suit'] = 1;
        	} else {
        		$v['is_suit'] = 0;
        	}
        	$return[] = $v;
        }
        return $return;
	}
	
	public function isSuit($itemid)
	{
		$productAttr = new CProductattr();
		$uid = isset($_COOKIE[COOKIE_PRE . 'uid']) ? $_COOKIE[COOKIE_PRE . 'uid'] : 0;
		if ($productAttr->getAttr($itemid, 12) || $productAttr->getAttr($itemid, 11)) {
			 $flashSale = new CFlashsales();
			if ($flashSale->isFlashItem($itemid)) {
				return true;
			}
			if ($this->isUserFlashItem($uid, $itemid)) {
				return true;
			}
			if ($this->isUserWhenEverFlashItem($uid, $itemid)) {
				return true;
			}
		}
		return false;
		
	}
}